package flc.ast.activity;

import android.graphics.Canvas;
import android.graphics.pdf.PdfDocument;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.io.FileOutputStream;
import java.io.IOException;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityPreviewBinding;
import flc.ast.utils.Content;
import flc.ast.utils.ResumePdfGenerateUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;

public class PreviewActivity extends BaseAc<ActivityPreviewBinding> {

    public static String response;
    private String pdfPath;

    @Override
    protected int onCreate() {
        return R.layout.activity_preview;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPreviewBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvDownload.setOnClickListener(this);
        mDataBinding.tvShare.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.tvDownload) {//下载
            String savePath = PathUtils.getExternalDownloadsPath() + "/" + getPackageName() + "/" + FileUtils.getFileName(pdfPath);
            FileUtils.copy(pdfPath, savePath);
            ToastUtils.showShort(getString(R.string.save_success));
            finish();
        } else if (id == R.id.tvShare) {//分享
            IntentUtil.shareFile(mContext, pdfPath);
        }
    }

    @Override
    protected void initData() {
        pdfPath = FileUtil.generateFilePath(Content.myTemp, ".pdf");
//        // 配置WebSettings
//        WebSettings webSettings = mDataBinding.webView.getSettings();
//        webSettings.setJavaScriptEnabled(true); // 启用JavaScript
//        webSettings.setDomStorageEnabled(true); // 启用DOM存储
//        webSettings.setDefaultTextEncodingName("UTF-8"); // 设置编码
//        webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR); // 尝试缩小初始显示
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // 强制单列布局（API 28+已弃用，但仍可尝试）
//
//        mDataBinding.webView.setInitialScale(90);
//
//        // 关键设置：让WebView支持<meta>标签的viewport属性
//        webSettings.setUseWideViewPort(true);
//
//        // 缩放到屏幕大小
//        webSettings.setLoadWithOverviewMode(true);
//
//        // 启用内置缩放控件（可选）
//        webSettings.setBuiltInZoomControls(true);
//        webSettings.setDisplayZoomControls(false); // 隐藏默认缩放按钮
//
//        showDialog(getString(R.string.loading));
//        //加载HTML字符串
//        mDataBinding.webView.loadDataWithBaseURL(null, response, "text/html", "UTF-8", null);
//
//        // 在WebView加载完成后调用
//        mDataBinding.webView.setWebViewClient(new WebViewClient() {
//            @Override
//            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
//                // 调用JS方法并获取返回值
//                generatePdfFunction();
//            }
//        });
        showDialog(getString(R.string.loading));
        new ResumePdfGenerateUtil(this, mDataBinding.webView).
                loadHtmlAndGeneratePdf(response, pdfPath, new ResumePdfGenerateUtil.OnPdfGeneratedListener() {
                    @Override
                    public void onSuccess(String pdfPath) {
                        dismissDialog();
                    }

                    @Override
                    public void onFailure(Exception e) {
                        dismissDialog();
                        ToastUtils.showShort(e.getMessage());
                    }
                });
    }

    // 封装调用JS的方法
    private void generatePdfFunction() {
        mDataBinding.webView.evaluateJavascript("onGeneratePDF();", null);
        new Handler().postDelayed(() -> {
            mDataBinding.webView.evaluateJavascript("window.pdfData", value -> {
                // value 是 base64 字符串，加了双引号
                if (value != null && value.length() > 0) {
                    String base64 = value.replaceAll("^\"|\"$", ""); // 去除首尾引号
                    String pureBase64 = base64.replaceFirst("data:application/pdf;filename=generated.pdf;base64,", "");
                    byte[] pdfBytes = Base64.decode(pureBase64, Base64.DEFAULT);

                    // 保存为本地文件
                    try {
                        FileOutputStream fos = new FileOutputStream(pdfPath);
                        fos.write(pdfBytes);
                        fos.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                }
            });
        }, 2000);
        dismissDialog();
    }

    public void generatePdfFromHtml(String html, String outputPath) {
        // 启用JavaScript支持
        WebSettings webSettings = mDataBinding.webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        // 加载HTML内容
        mDataBinding.webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);

        generatePdfWithMultiplePages(mDataBinding.webView, outputPath);
    }

    private void generatePdfWithMultiplePages(WebView webView, String outputPath) {
        // 设置WebView客户端监听页面加载完成
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 添加延迟确保内容完全渲染
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    generatePdfAfterPageLoad(view, outputPath);
                }, 1000); // 1秒延迟
            }
        });
    }

    private void generatePdfAfterPageLoad(WebView webView, String outputPath) {
        try {
            WebSettings settings = webView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setDomStorageEnabled(true);
            settings.setLoadWithOverviewMode(true);
            settings.setUseWideViewPort(true);

            // 关键修改1：解除WebView宽度限制，允许内容自然展开
            ViewGroup.LayoutParams params = webView.getLayoutParams();
            params.width = ViewGroup.LayoutParams.WRAP_CONTENT; // 让内容决定宽度
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            webView.setLayoutParams(params);
            webView.requestLayout(); // 强制重新布局

            // 关键修改2：通过JavaScript获取实际内容宽度（而非屏幕宽度）
            webView.evaluateJavascript("(function(){return Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);})()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    try {
                        // 解析JavaScript返回的内容宽度
                        int contentWidth = Integer.parseInt(value);
                        ToastUtils.showShort(contentWidth + "");
                        // 容错处理：如果获取失败则使用默认宽度
                        if (contentWidth <= 0) contentWidth = 794; // A4宽度作为保底

                        // 计算内容高度（使用WebView提供的内容高度）
                        int contentHeight = (int) (webView.getContentHeight() * webView.getScale());

                        // PDF页面设置（A4尺寸：595x842点）
                        int a4PageWidth = 794;
                        float scaleFactor = (float) a4PageWidth / contentWidth; // 基于内容宽度计算缩放
                        int pageHeight = 1122;

                        // 计算缩放后的内容高度和总页数
                        int scaledContentHeight = (int) (contentHeight * scaleFactor);
                        int totalPages = (int) Math.ceil((float) scaledContentHeight / pageHeight);

                        PdfDocument pdfDocument = new PdfDocument();
                        int pageNumber = 1;
                        int yOffset = 0;

                        // 处理分页并绘制内容
                        while (yOffset < scaledContentHeight) {
                            int currentPageHeight = Math.min(scaledContentHeight - yOffset, pageHeight);
                            PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(a4PageWidth, currentPageHeight, pageNumber).create();
                            PdfDocument.Page page = pdfDocument.startPage(pageInfo);
                            Canvas canvas = page.getCanvas();

                            // 应用缩放并绘制当前页内容
                            canvas.save();
                            canvas.scale(scaleFactor, scaleFactor);
                            canvas.translate(0, -yOffset / scaleFactor);
                            webView.draw(canvas);
                            canvas.restore();

                            pdfDocument.finishPage(page);
                            yOffset += currentPageHeight;
                            pageNumber++;
                        }

                        // 保存PDF文件
                        pdfDocument.writeTo(new FileOutputStream(outputPath));
                        pdfDocument.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        FileUtils.deleteAllInDir(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
    }

}